﻿using DoNet.System.IServices;
using Microsoft.AspNetCore.Http;

namespace DoNet.Extensions.Middlewares
{
    /// <summary>
    /// Swagger UI 访问需要登录才能访问
    /// </summary>
    public class SwaggerBasicAuthMiddleware
    {
        private readonly ITokenService tokenService;
        private readonly RequestDelegate next;

        public SwaggerBasicAuthMiddleware(RequestDelegate next, ITokenService _tokenService)
        {
            this.next = next;
            tokenService = _tokenService;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            string path = context.Request.Path.Value ?? string.Empty;
            // 也可以根据是否是本地做判断 IsLocalRequest
            if (path.ToLower().Contains("index.html"))
            {
                // 判断权限是否正确
                if (IsAuthorized(context))
                {
                    await next.Invoke(context);
                    return;
                }

                // 无权限，跳转swagger登录页
                context.Response.Redirect("/swg-login.html");
            }
            else
            {
                await next.Invoke(context);
            }
        }

        public bool IsAuthorized(HttpContext context)
        {
            // 使用session模式
            // 可以使用其他的
            var token = context.Request.Cookies["donet_soft_token"];
            if (!string.IsNullOrEmpty(token))
            {
                return tokenService.ValidateToken(token);
            }
            return false;
        }
    }
}
